package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.approval.vo.ApproFlowListVO;
import org.jsola.common.DateKit8;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.ApprovalStatusEnum;
import org.jsola.hr.constant.EmpChangeType;
import org.jsola.hr.constant.EmpInfoStatus;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.ConfirmLeaveOfficeDTO;
import org.jsola.hr.dto.EmpChangesAddDTO;
import org.jsola.hr.dto.EmpChangesUpdateDTO;
import org.jsola.hr.dto.excel.EmpChangeImportDTO;
import org.jsola.hr.entity.EmpInfoDO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.provider.IApproProviderService;
import org.jsola.hr.query.EmpChangesQuery;
import org.jsola.hr.query.EmpSocTransformQuery;
import org.jsola.hr.service.IEmpChangesService;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.vo.*;
import org.jsola.hr.vo.excel.ParseResultVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * @author zhr
 */
@RestController("hrEmpChangesController")
@RequestMapping(HrConstants.API_PATH + "/v1/empChanges")
public class EmpChangesController implements IEmpChangesControllerAPI {

    @Autowired
    private IEmpChangesService empChangesService;

    @Autowired
    private IEmpInfoService empInfoService;

    @Autowired
    private IApproProviderService approProviderService;

    @Override
    @PostMapping
    public Result<EmpChangesVO> save(@Valid @RequestBody EmpChangesAddDTO empChangesAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工人事变动记录权限校验

        if (empChangesAddDTO.getChangeType() == null) {
            return Result.fail("请填写员工变动类型");
        } else if (EmpChangeType.find(empChangesAddDTO.getChangeType()) == null) {
            return Result.fail("请填写正确的员工变动类型");
        }
        return Result.success(
                empChangesService.save(empChangesAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody EmpChangesUpdateDTO empChangesUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改员工人事变动记录权限校验

        int count = empChangesService.update(empChangesUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{empChangesId}")
    public Result<Integer> delete(@PathVariable String empChangesId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除员工人事变动记录权限校验

        int count = empChangesService.deleteByIds(tokenUser, empChangesId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] empChangesIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除员工人事变动记录权限校验

        int count = empChangesService.deleteByIds(tokenUser, empChangesIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{empChangesId}")
    public Result<EmpChangesVO> findById(@PathVariable String empChangesId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看员工人事变动记录权限校验

        return Result.success(
                empChangesService.selectById(empChangesId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<EmpChangesListVO>> listAll(@Valid EmpChangesQuery empChangesQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看员工人事变动记录权限校验

        return Result.success(
                empChangesService.select(empChangesQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<EmpChangesListVO>> page(@Valid EmpChangesQuery empChangesQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empChangesService.selectPage(empChangesQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping(value = "/transferFormal")
    public Result<EmpChangesVO> transferFormal(@Valid @RequestBody EmpChangesAddDTO empChangesAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工入职信息权限校验
        // 转正式
        empChangesAddDTO.setChangeType(EmpChangeType.TRANSFER__FORMAL.getValue());

        return Optional.ofNullable(empChangesService.transferFormal(empChangesAddDTO, tokenUser))
                .map(vo -> Result.success(vo))
                .orElseGet(() -> Result.fail("转正式操作失败"));
    }

    @Override
    @PostMapping(value = "/batchTransferRegular")
    public Result<String> batchTransferRegular(@Valid EmpChangesAddDTO empChangesAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // 转正
        empChangesAddDTO.setChangeType(EmpChangeType.TRANSFER__REGULAR.getValue());
        // 获取转正审批
        List<ApproFlowListVO> approFlowList = approProviderService.listTurnStraightCanUseFlowsByCompany(empChangesAddDTO.getCompanyId(), tokenUser);
        if (CollectionUtils.isEmpty(approFlowList)) {
            empChangesAddDTO.setApproFlowId(null);
            // 不需要审批,直接保存
            empChangesService.batchTransferRegular(empChangesAddDTO, tokenUser);
            return Result.success("员工转正成功,到达预设转正日期时,员工会转为正式员工");
        } else {
            // 走转正审批
            String approFlowId = empChangesAddDTO.getApproFlowId();
            if (StringUtils.isEmpty(approFlowId)) {
                if (approFlowList.size() > 1) {
                    return Result.fail("请先选择合适的转正审批流程");
                }
                approFlowId = approFlowList.get(0).getId();
                empChangesAddDTO.setApproFlowId(approFlowId);
            }
            empChangesService.batchTransferRegular(empChangesAddDTO, tokenUser);
            return Result.success("员工转正申请提交成功,审批通过并到达预设转正日期时,员工会转为正式员工");
        }
    }

    @Override
    @PostMapping(value = "/transferRegular")
    public Result<String> transferRegular(@Valid @RequestBody EmpChangesAddDTO empChangesAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工入职信息权限校验

        // 转正
        empChangesAddDTO.setChangeType(EmpChangeType.TRANSFER__REGULAR.getValue());

        String empId = empChangesAddDTO.getEmpId();
        EmpInfoVO empInfoVO = empInfoService.selectById(empId, tokenUser.getSiteId());
        if (Objects.isNull(empInfoVO)) {
            return Result.fail("待转正的员工不存在或已删除,请检查");
        } else {
            if (empInfoVO.getStatus() < EmpInfoStatus.HAS_ENTRY.getValue()) {
                return Result.fail("员工尚未确认到岗,请先确认员工已到岗");
            }
            if (!empInfoVO.getFormalType().equals(1)) {
                return Result.fail("员工已不是试用期不需要进行转正");
            }
            // 获取转正审批
            List<ApproFlowListVO> approFlowList = approProviderService.listTurnStraightCanUseFlowsByCompany(empChangesAddDTO.getCompanyId(), tokenUser);
            if (CollectionUtils.isEmpty(approFlowList)) {
                empChangesAddDTO.setApproFlowId(null);
                // 不需要审批,直接保存
                empChangesService.transferRegular(empChangesAddDTO, tokenUser);
                return Result.success("员工转正成功,到达预设转正日期时,员工会转为正式员工");
            } else {
                // 走转正审批
                String approFlowId = empChangesAddDTO.getApproFlowId();
                if (StringUtils.isEmpty(approFlowId)) {
                    if (approFlowList.size() > 1) {
                        return Result.fail("请先选择合适的转正审批流程");
                    }
                    approFlowId = approFlowList.get(0).getId();
                    empChangesAddDTO.setApproFlowId(approFlowId);
                }
                empChangesService.transferRegular(empChangesAddDTO, tokenUser);
                return Result.success("员工转正申请提交成功,审批通过并到达预设转正日期时,员工会转为正式员工");
            }
        }
    }

    @Override
    @PostMapping(value = "/batchTransferPosition")
    public Result<String> batchTransferPosition(@Valid EmpChangesAddDTO empChangesAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工入职信息权限校验

        // 调岗
        empChangesAddDTO.setChangeType(EmpChangeType.TRANSFER__POSITION.getValue());

        // 获取调岗审批
        List<ApproFlowListVO> approFlowList = approProviderService.listTransferDutyCanUseFlowsByCompany(empChangesAddDTO.getCompanyId(), tokenUser);
        if (CollectionUtils.isEmpty(approFlowList)) {
            empChangesAddDTO.setApproFlowId(null);
            // 不需要审批,直接保存
            empChangesService.batchTransferPosition(empChangesAddDTO, tokenUser);
            return Result.success("员工申请调岗成功");
        } else {
            // 走调岗审批
            String approFlowId = empChangesAddDTO.getApproFlowId();
            if (StringUtils.isEmpty(approFlowId)) {
                if (approFlowList.size() > 1) {
                    return Result.fail("请先选择合适的调岗审批流程");
                }
                approFlowId = approFlowList.get(0).getId();
                empChangesAddDTO.setApproFlowId(approFlowId);
            }
            empChangesService.batchTransferPosition(empChangesAddDTO, tokenUser);
            return Result.success("员工调岗申请提交成功,请耐心等待审批结果");
        }

    }

    @Override
    @PostMapping(value = "/transferPosition")
    public Result<String> transferPosition(@Valid @RequestBody EmpChangesAddDTO empChangesAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工入职信息权限校验

        // 调岗
        empChangesAddDTO.setChangeType(EmpChangeType.TRANSFER__POSITION.getValue());

        String empId = empChangesAddDTO.getEmpId();
        EmpInfoVO empInfoVO = empInfoService.selectById(empId, tokenUser.getSiteId());
        if (Objects.isNull(empInfoVO)) {
            return Result.fail("待调岗的员工不存在或已删除,请检查");
        } else {
            if (empInfoVO.getStatus() < EmpInfoStatus.HAS_ENTRY.getValue()) {
                return Result.fail("员工尚未确认到岗,请先确认员工已到岗");
            }
            if (!empInfoVO.getChangeStatus().equals(0)) {
                return Result.fail("员工正在进行其他操作,待其结束后再进行调岗操作");
            }
            // 获取调岗审批
            List<ApproFlowListVO> approFlowList = approProviderService.listTransferDutyCanUseFlowsByCompany(empChangesAddDTO.getCompanyId(), tokenUser);
            if (CollectionUtils.isEmpty(approFlowList)) {
                empChangesAddDTO.setApproFlowId(null);
                // 不需要审批,直接保存
                empChangesService.transferPosition(empChangesAddDTO, tokenUser);
                return Result.success("员工申请调岗成功");
            } else {
                // 走调岗审批
                String approFlowId = empChangesAddDTO.getApproFlowId();
                if (StringUtils.isEmpty(approFlowId)) {
                    if (approFlowList.size() > 1) {
                        return Result.fail("请先选择合适的调岗审批流程");
                    }
                    approFlowId = approFlowList.get(0).getId();
                    empChangesAddDTO.setApproFlowId(approFlowId);
                }
                empChangesService.transferPosition(empChangesAddDTO, tokenUser);
                return Result.success("员工调岗申请提交成功,请耐心等待审批结果");
            }
        }
    }

    @Override
    @PutMapping(value = "/confim/transferPosition/{empChangesId}")
    public Result<Integer> confirmTransferPosition(@PathVariable String empChangesId) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                empChangesService.confirmTransferPositionByChangesId(empChangesId, tokenUser));
    }

    @Override
    @PutMapping(value = "/revoke/transferPosition/{empChangesId}")
    public Result<String> revokeTransferPosition(@PathVariable String empChangesId) {
        return revokeTransferPositionByChangesId(empChangesId);
    }

    @Override
    @PutMapping(value = "/confimByEmp/transferPosition/{empId}")
    public Result<Integer> confimTransferPositionByEmpId(@PathVariable String empId) {
        TokenUser tokenUser = UserContext.getUser();

        String empChangesId = empChangesService.getLastChangesId(empId, EmpChangeType.TRANSFER__POSITION.getValue(), tokenUser.getSiteId());
        if (StringUtils.isEmpty(empChangesId)) {
            return Result.fail("暂无员工调岗申请,无法确认");
        }
        return Result.success(
                empChangesService.confirmTransferPositionByChangesId(empChangesId,tokenUser)
        );
    }

    @Override
    @PutMapping(value = "/batchConfirmTransferPosition")
    public Result<Integer> batchConfirmTransferPosition(@RequestBody String[] empIds) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                empChangesService.batchConfirmTransferPosition(empIds, tokenUser)
        );
    }

    @Override
    @PutMapping(value = "/batchRevokeTransferPositionByEmpId")
    public Result<String> batchRevokeTransferPositionByEmpId(@Valid @RequestBody String[] empIds) {
        TokenUser tokenUser = UserContext.getUser();
        Result<String> stringResult = null;
        for (String empId : empIds) {
            String empChangesId = empChangesService.getLastChangesId(empId, EmpChangeType.TRANSFER__POSITION.getValue(), tokenUser.getSiteId());
            if (StringUtils.isEmpty(empChangesId)) {
                return Result.fail("暂无员工调岗申请,无法撤销");
            }
            stringResult = revokeTransferPositionByChangesId(empChangesId);
        }
        return stringResult;
    }

    @Override
    @PutMapping(value = "/revokeByEmp/transferPosition/{empId}")
    public Result<String> revokeTransferPositionByEmpId(@PathVariable String empId) {
        TokenUser tokenUser = UserContext.getUser();

        String empChangesId = empChangesService.getLastChangesId(empId, EmpChangeType.TRANSFER__POSITION.getValue(), tokenUser.getSiteId());
        if (StringUtils.isEmpty(empChangesId)) {
            return Result.fail("暂无员工调岗申请,无法撤销");
        }
        return revokeTransferPositionByChangesId(empChangesId);
    }

    /**
     * 根据员工变更id撤销调岗申请
     *
     * @param empChangesId 员工变更id
     * @return 结果
     */
    private Result<String> revokeTransferPositionByChangesId(String empChangesId) {
        TokenUser tokenUser = UserContext.getUser();

        EmpChangesVO empChangesVO = empChangesService.selectById(empChangesId, tokenUser.getSiteId());
        if (Objects.isNull(empChangesVO)) {
            return Result.fail("调岗申请不存在或已删除");
        } else {
            String empId = empChangesVO.getEmpId();
            EmpInfoVO empInfoVO = empInfoService.selectById(empId, tokenUser.getSiteId());
            if (Objects.isNull(empInfoVO)) {
                return Result.fail("调岗员工不存在或已删除,请检查");
            } else if (!empInfoVO.getChangeStatus().equals(2)) {
                // 员工变动状态（0：当前无变动，1：转正中，2：调岗中，3： 离职中）
                return Result.fail("调岗员工状态不是调岗中,不需要撤销");
            } else if (empInfoVO.getApprovalStatus().equals(ApprovalStatusEnum.APPRO_ING.getValue())) {
                // 审批状态 审批通过或不需要审批
                return Result.fail("申请已开始审批,请等待审批结束后再进行撤销");
            }
            empChangesService.revokeTransferPosition(empChangesId, tokenUser);
            return Result.success("撤回调岗成功");
        }
    }

    @Override
    @PostMapping(value = "/batchLeavePosition")
    public Result<String> batchLeavePosition(@Valid EmpChangesAddDTO empChangesAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // 离职
        empChangesAddDTO.setChangeType(EmpChangeType.LEAVE.getValue());

        // 获取离职审批
        List<ApproFlowListVO> approFlowList = approProviderService.listLeavingCanUseFlowsByCompany(empChangesAddDTO.getCompanyId(), tokenUser);
        if (CollectionUtils.isEmpty(approFlowList)) {
            empChangesAddDTO.setApproFlowId(null);
            // 不需要审批,直接保存
            empChangesService.batchLeavePosition(empChangesAddDTO, tokenUser);
            return Result.success("员工离职成功");
        } else {
            // 走离职审批
            String approFlowId = empChangesAddDTO.getApproFlowId();
            if (StringUtils.isEmpty(approFlowId)) {
                if (approFlowList.size() > 1) {
                    return Result.fail("请先选择合适的离职审批流程");
                }
                approFlowId = approFlowList.get(0).getId();
                empChangesAddDTO.setApproFlowId(approFlowId);
            }
            empChangesService.batchLeavePosition(empChangesAddDTO, tokenUser);
            return Result.success("员工离职申请提交成功,请耐心等待审批结果");
        }

    }

    @Override
    @PostMapping(value = "/leavePosition")
    public Result<String> leavePosition(@Valid @RequestBody EmpChangesAddDTO empChangesAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工入职信息权限校验

        // 离职
        empChangesAddDTO.setChangeType(EmpChangeType.LEAVE.getValue());

        String empId = empChangesAddDTO.getEmpId();
        EmpInfoVO empInfoVO = empInfoService.selectById(empId, tokenUser.getSiteId());
        if (Objects.isNull(empInfoVO)) {
            return Result.fail("待离职的员工不存在或已删除,请检查");
        } else {
            if (empInfoVO.getStatus() < EmpInfoStatus.HAS_ENTRY.getValue()) {
                return Result.fail("员工尚未确认到岗,请先确认员工已到岗");
            }
            if (!empInfoVO.getChangeStatus().equals(0)) {
                return Result.fail("员工正在进行其他操作,待其结束后再进行离职操作");
            }
            // 获取离职审批
            List<ApproFlowListVO> approFlowList = approProviderService.listLeavingCanUseFlowsByCompany(empChangesAddDTO.getCompanyId(), tokenUser);
            if (CollectionUtils.isEmpty(approFlowList)) {
                empChangesAddDTO.setApproFlowId(null);
                // 不需要审批,直接保存
                empChangesService.leavePosition(empChangesAddDTO, tokenUser);
                return Result.success("员工离职成功");
            } else {
                // 走离职审批
                String approFlowId = empChangesAddDTO.getApproFlowId();
                if (StringUtils.isEmpty(approFlowId)) {
                    if (approFlowList.size() > 1) {
                        return Result.fail("请先选择合适的离职审批流程");
                    }
                    approFlowId = approFlowList.get(0).getId();
                    empChangesAddDTO.setApproFlowId(approFlowId);
                }
                empChangesService.leavePosition(empChangesAddDTO, tokenUser);
                return Result.success("员工离职申请提交成功,请耐心等待审批结果");
            }
        }
    }

    @Override
    @PutMapping(value = "/confim/leave/{empChangesId}")
    public Result<String> confimLeave(@PathVariable String empChangesId) {
        return confimLeaveByEmpChangesId(empChangesId);
    }

    @Override
    @PutMapping(value = "/revoke/leave/{empChangesId}")
    public Result<String> revokeLeave(@PathVariable String empChangesId) {
        return revokeLeaveByEmpChangesId(empChangesId);
    }

    @Override
    @PostMapping(value = "/confimByEmp/leave/{empId}")
    public Result<List<ConfirmLeaveOfficeListVO>> confirmLeaveByEmpId(@RequestBody ConfirmLeaveOfficeDTO confirmLeaveOfficeDTO,
                                                                      @PathVariable String empId) {
        TokenUser tokenUser = UserContext.getUser();

        String empChangesId = empChangesService.getLastChangesId(empId, EmpChangeType.LEAVE.getValue(), tokenUser.getSiteId());
        if (StringUtils.isEmpty(empChangesId)) {
            return Result.fail("暂无员工离职申请,无法确认");
        }
        confirmLeaveOfficeDTO.setEmpChangesId(empChangesId);
        return Result.success(
                empChangesService.checkAndConfirmLeaveOffice(confirmLeaveOfficeDTO, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/confimByEmp/leave/batch")
    public Result<List<ConfirmLeaveOfficeListVO>> confirmLeaveByEmpIds(@RequestBody ConfirmLeaveOfficeDTO confirmLeaveOfficeDTO) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                empChangesService.checkAndConfirmLeaveOfficeBatch(confirmLeaveOfficeDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportErrorList")
    public ResponseEntity<Resource> exportErrorList(@Valid @RequestBody ImportExcelResultListVO<EmpChangeImportDTO> errorList) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工参保信息表权限校验
        String excelFilePath = empChangesService.exportErrorList(errorList, tokenUser);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @PostMapping("/importExcel")
    public Result<ImportExcelResultListVO<EmpChangeImportDTO>> importEmpChangeFile(@RequestParam("file") MultipartFile file,
                                                                                   @RequestParam("companyId") String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导入解析excel权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                empChangesService.importEmpChangeFile(excelFile, companyId, tokenUser)
        );
    }

    /**
     * 根据员工变更id确认离职
     *
     * @param empChangesId 员工变更id
     * @return 结果
     */
    private Result<String> confimLeaveByEmpChangesId(String empChangesId) {
        TokenUser tokenUser = UserContext.getUser();

        EmpChangesVO empChangesVO = empChangesService.selectById(empChangesId, tokenUser.getSiteId());
        if (Objects.isNull(empChangesVO)) {
            return Result.fail("离职申请不存在或已删除");
        } else {
            String empId = empChangesVO.getEmpId();
            EmpInfoVO empInfoVO = empInfoService.selectById(empId, tokenUser.getSiteId());
            if (Objects.isNull(empInfoVO)) {
                return Result.fail("离职员工不存在或已删除,请检查");
            } else if (!empInfoVO.getChangeStatus().equals(3)) {
                // 员工变动状态（0：当前无变动，1：转正中，2：调岗中，3： 离职中）
                return Result.fail("离职员工状态不是离职中,不需要确认");
            } else if (!empInfoVO.getApprovalStatus().equals(ApprovalStatusEnum.APPRO_SUCCESS.getValue())
                    && !empInfoVO.getApprovalStatus().equals(ApprovalStatusEnum.APPRO_DISABLE.getValue())) {
                // 审批状态 审批通过或不需要审批
                return Result.fail("申请尚未审核通过,不能确认");
            }
            empChangesService.confirmLeave(empChangesId, tokenUser);
            return Result.success("确认离职成功");
        }
    }

    @Override
    @PutMapping("/batchRevokeLeaveByEmpId")
    public Result<String> batchRevokeLeaveByEmpId(@RequestBody String[] empIds) {
        TokenUser tokenUser = UserContext.getUser();
        Result<String> stringResult = null;
        for (String empId : empIds) {
            String empChangesId = empChangesService.getLastChangesId(empId, EmpChangeType.LEAVE.getValue(), tokenUser.getSiteId());
            if (StringUtils.isEmpty(empChangesId)) {
                return Result.fail("暂无员工离职申请,无法撤销");
            }
            stringResult = revokeLeaveByEmpChangesId(empChangesId);
        }
        return stringResult;
    }

    @Override
    @PutMapping(value = "/revokeByEmp/leave/{empId}")
    public Result<String> revokeLeaveByEmpId(@PathVariable String empId) {
        TokenUser tokenUser = UserContext.getUser();

        String empChangesId = empChangesService.getLastChangesId(empId, EmpChangeType.LEAVE.getValue(), tokenUser.getSiteId());
        if (StringUtils.isEmpty(empChangesId)) {
            return Result.fail("暂无员工离职申请,无法撤销");
        }
        return revokeLeaveByEmpChangesId(empChangesId);
    }

    /**
     * 根据员工变更id撤销离职
     *
     * @param empChangesId 员工变更id
     * @return 结果
     */
    private Result<String> revokeLeaveByEmpChangesId(String empChangesId) {
        TokenUser tokenUser = UserContext.getUser();

        EmpChangesVO empChangesVO = empChangesService.selectById(empChangesId, tokenUser.getSiteId());
        if (Objects.isNull(empChangesVO)) {
            return Result.fail("离职申请不存在或已删除");
        } else {
            String empId = empChangesVO.getEmpId();
            EmpInfoVO empInfoVO = empInfoService.selectById(empId, tokenUser.getSiteId());
            if (Objects.isNull(empInfoVO)) {
                return Result.fail("离职员工不存在或已删除,请检查");
            } else if (!empInfoVO.getChangeStatus().equals(3)) {
                // 员工变动状态（0：当前无变动，1：转正中，2：调岗中，3： 离职中）
                return Result.fail("离职员工状态不是离职中,不需要撤销");
            } else if (empInfoVO.getApprovalStatus().equals(ApprovalStatusEnum.APPRO_ING.getValue())) {
                // 审批状态 审批通过或不需要审批
                return Result.fail("申请已开始审批,请等待审批结束后再进行撤销");
            }
            empChangesService.revokeLeave(empChangesId, tokenUser);
            //人员变动发送通知
            empInfoService.sendNotice(empInfoVO.to(EmpInfoDO.class),tokenUser);
            return Result.success("撤回离职成功");
        }
    }

    @Override
    @GetMapping(value = "/pageEmpResignedList/{companyId}")
    public Result<Page<EmpChangesRelationVO>> pageEmpResignedList(
            @PathVariable String companyId,
            @Valid EmpChangesQuery empChangesQuery) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                empChangesService.pageEmpResignedList(companyId,empChangesQuery.getEmpName(),
                        empChangesQuery.getPageNo(), empChangesQuery.getPageSize(), tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/pageEmpTransferList/{companyId}")
    public Result<Page<EmpChangesRelationVO>> pageEmpTransferList(
            @PathVariable String companyId,
            @Valid EmpChangesQuery empChangesQuery) {

        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                empChangesService.pageEmpTransferList(companyId,empChangesQuery.getEmpName()
                        , empChangesQuery.getPageNo(), empChangesQuery.getPageSize(), tokenUser.getSiteId())
        );
    }
}

